/**
 *  
 *  加载UI，可以在theme没装载之前加载
 *
 */
class LoadingView extends BaseEuiView {
    public loadingRun: eui.Image;
    public loadingText: eui.Label;
    public loadingBg: eui.Image;
    public loadingRunPATH: string = Resource.getAssets() + "Load/loading.png";
    public loadingBgPATH: string;
    
    private resIsLoaded : boolean = false;

    protected initUI(): void {
        this.left = this.right = this.bottom = this.top = 0;
        this.loadAsset(this.loadingRunPATH,this.loadingComplete,this);
    }

    public setBgRes(source: string): void {
        this.loadingBg.visible = true;
        this.loadingBgPATH = source;
        this.loadAsset(source,this.loadingComplete,this);
    }

    public setProgress(itemsLoaded: number,itemsTotal: number): void {        if(this.loadingText != null) {
            this.loadingText.text = Math.round(itemsLoaded / itemsTotal * 100) + "%";
        }    }
    /**
     * 展示
     */ 
    public show(): void{
        if(this.resIsLoaded){
            this.initLoadingView();
        }else{
            this.initUI();
        }
    }
    
    private loadingComplete(texture: egret.Texture,source: string) {
        if(source == this.loadingBgPATH) {
            this.loadingBg.source = texture;
        }
        else if(source == this.loadingRunPATH) {
            this.loadingText.text = "0%";
            this.loadingRun.source = texture;
            this.initLoadingView();
        }
    }
    
    
    private initLoadingView():void{
        this.loadingRun.x = Context.getInstance().getWidth() / 2;
        this.loadingRun.y = Context.getInstance().getHeight() / 2;
        this.setAnchor(this.loadingRun,this.loadingRun.width * 0.5,this.loadingRun.height * 0.5);
        this.addEventListener(egret.Event.REMOVED_FROM_STAGE,() => {
            if(this.hasEventListener(egret.Event.ENTER_FRAME)) {                this.removeEventListener(egret.Event.ENTER_FRAME,this.runLoading,this);            }        },this);
        this.addEventListener(egret.Event.ENTER_FRAME,this.runLoading,this);
    }
    

    private runLoading(evt: egret.Event) {
        this.loadingRun.rotation += 3;    }

    protected exml(): string {
        return Resource.getDefaultExmlDir() + "LoadingSkin.exml";
    }

}
